package org.example.content.service.Impl;

import org.example.content.mapper.CourseCategoryMapper;
import org.example.content.model.dto.CourseCategoryTreeDto;
import org.example.content.service.CourseCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Service
public class CourseCategoryServiceImpl implements CourseCategoryService {
    @Autowired
    CourseCategoryMapper courseCategoryMapper;
    @Override
    public List<CourseCategoryTreeDto> selectTreeNodes(String id) {
       //调用mapper递归查询
    List<CourseCategoryTreeDto> courseCategoryTreeDtos = courseCategoryMapper.selectTreeNodes(id);
    //找到子节点,封装成List<CourseCategoryTreeDto>
    Map<String,CourseCategoryTreeDto> mapTemp=courseCategoryTreeDtos.stream().filter(item->!id.equals(item.getId())).collect(Collectors.toMap(key->key.getId(), value->value,(k1, k2)->k2));
    //定义一个可以返回的集合
    List<CourseCategoryTreeDto> courseCategoryList=new ArrayList<CourseCategoryTreeDto>();

    courseCategoryTreeDtos.forEach(item->{
        if(item.getParentid().equals(id)){
            courseCategoryList.add(item);
        }
        //将子节点，放到父节点的childNodes中
        CourseCategoryTreeDto courseCategoryTreeDto=mapTemp.get(item.getParentid());
        if(courseCategoryTreeDto!=null){
            if(courseCategoryTreeDto.getChildrenTreeNodes()==null){
                //如果父节点的属性为空，new一个集合，放他的子节点
                courseCategoryTreeDto.setChildrenTreeNodes(new ArrayList<CourseCategoryTreeDto>());
            }
            //每个子节点放入父节点中
            courseCategoryTreeDto.getChildrenTreeNodes().add(item);
        }



    });
    return courseCategoryList;

    }
}
